import axios from './request'
import Vue from 'vue'
// import {Indicator, Toast} from 'mint-ui'
import {ToastPlugin, LoadingPlugin} from 'vux'

Vue.use(ToastPlugin)
Vue.use(LoadingPlugin)

/*
* 存放全局公用方法
*/

// 获取cookie
function getCookie(name) {
    let arr, reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
    if (document.cookie.match(reg)) {
        arr = document.cookie.match(reg)
        return unescape(arr[2])
    } else {
        return null
    }
}

// 获取系统类型
function getSystem() {
    let u = navigator.userAgent, isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1,
        isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    return {
        isAndroid,
        isiOS
    }
}

// 获取浏览器类型
function getBrowser() {
    let ua = navigator.userAgent.toLowerCase(),
        isWx = /micromessenger/i.test(ua),
        isAli = /alipay/i.test(ua),
        isBd = /baidu/i.test(ua)
    return {
        isWx,
        isAli,
        isBd
    }
}

// 获取数据类型
function typeObj(obj) {
    let type = Object.prototype.toString.call(obj)
    if (type === '[object Array]') {
        return 'array'
    } else if (type === '[object Object]') {
        return 'object'
    } else {
        return 'other'
    }
}

// 对数据进行深复制
function deepClone(data) {
    let type = typeObj(data), obj
    if (type === 'array') {
        obj = []
    } else if (type === 'object') {
        obj = {}
    } else {
        return data
    }
    if (type === 'array') {
        for (let i = 0, len = data.length; i < len; i++) {
            obj.push(deepClone(data[i]))
        }
    } else if (type === 'object') {
        for (let key in data) {
            obj[key] = deepClone(data[key])
        }
    }
    return obj
}

export default {
    // 判断是否为array数组
    isArrayFn(value) {
        if (typeof Array.isArray === 'function') {
            return Array.isArray(value)
        } else {
            return Object.prototype.toString.call(value) === '[object Array]'
        }
    },
    // 获取url中的参数
    getUrlParam(name) {
        let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'), // 构造一个含有目标参数的正则表达式对象
            r = window.location.search.substr(1).match(reg) // 匹配目标参数

        if (r !== null) return decodeURIComponent(r[2])
        return null // 返回参数值
    },
    // 设置cookie
    setCookie(name, value) {
        let exp = new Date()
        exp.setTime(exp.getTime() + 60 * 60 * 1000)
        document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString() + ';path=/'
    },
    getCookie,
    // 删除cookie
    delCookie(name) {
        let exp = new Date(), cval
        exp.setTime(exp.getTime() - 60 * 60 * 1000)
        cval = getCookie(name)
        if (cval !== null) {
            document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString() + ';path=/'
        }
    },
    // 页面返回
    historyBack() {
        let route = window.$vm.$route, router = window.$vm.$router
        if (window.history.length < 2 || window.$history < 2) {
            router.push(route.matched[route.matched.length - 2].path || '/')
        } else {
            router.back(-1)
        }
    },
    // input失去焦点滚动条复原，用以解决ios输入法消失残留空白区域影响操作
    inputBlur() {
        window.scroll(0, 0)
    },
    // 微信api注册
    wxConfig() {
        let sys = getSystem(), wechaturl = (sys.isiOS ? window.wxurl : location.href).split('#')[0]
        axios.post('/wechat/createJsSdkSigniture?url=' + encodeURIComponent(wechaturl)).then(res => {
            window.$vm.$wechat.config({
                debug: false, // 开启调试模式,
                url: wechaturl,
                appId: res.data.appid, // 必填，企业号的唯一标识，此处填写企业号corpid
                timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                nonceStr: res.data.noncestr, // 必填，生成签名的随机串
                signature: res.data.signature, // 必填，签名
                jsApiList: ['scanQRCode', 'checkJsApi', 'chooseImage', 'uploadImage', 'getLocalImgData',
                    'downloadImage', 'previewImage', 'getLocalImgData'] // 必填，需要使用的JS接口列表
            })
            window.$vm.$wechat.error(function (error) {
                console.log('current url -- ' + wechaturl)
                console.log('config error -- ' + JSON.stringify(error))
            })
            window.$vm.$wechat.ready(function () {
                // window.$vm.$wechat.checkJsApi({
                //     jsApiList: ['scanQRCode'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
                //     success: function (res) {
                //         if (!res.checkResult || !res.checkResult.scanQRCode) {
                //             alert(JSON.stringify(res))
                //         }
                //     }
                // })
            })
        })
    },
    getSystem,
    getBrowser,
    typeObj,
    deepClone,
    showToast(text, position, time) {
        Vue.$vux.toast.show({
            text: text,
            position: position || 'middle',
            time: time || 3000
        })
    }
}
